/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.source.service.floor;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.source.dao.floor.EleSourceFloorDao;
import com.thinkgem.jeesite.modules.source.dao.floor.FloorDao;
import com.thinkgem.jeesite.modules.source.dao.floor.FloorNodeDao;
import com.thinkgem.jeesite.modules.source.entity.floor.EleSourceFloor;
import com.thinkgem.jeesite.modules.source.entity.floor.Floor;
import com.thinkgem.jeesite.modules.source.entity.floor.FloorNode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 楼层资源管理Service
 * @author ZC
 * @version 2017-06-22
 */
@Service
@Transactional(readOnly = true)
public class EleSourceFloorService extends CrudService<EleSourceFloorDao, EleSourceFloor> {

	@Autowired
	private FloorDao floorDao;
	@Autowired
	private FloorNodeDao floorNodeDao;
	
	public EleSourceFloor get(String id) {
		EleSourceFloor eleSourceFloor = super.get(id);
		eleSourceFloor.setFloors(floorDao.findList(new Floor(eleSourceFloor)));
		eleSourceFloor.setFloornodes(floorNodeDao.getByGroupId(id));
		return eleSourceFloor;
	}
	
	public List<EleSourceFloor> findList(EleSourceFloor eleSourceFloor) {
		return super.findList(eleSourceFloor);
	}
	
	public Page<EleSourceFloor> findPage(Page<EleSourceFloor> page, EleSourceFloor eleSourceFloor) {
		return super.findPage(page, eleSourceFloor);
	}
	
	@Transactional(readOnly = false)
	public void save(EleSourceFloor eleSourceFloor) {
		super.save(eleSourceFloor);
		for (Floor floor : eleSourceFloor.getFloors()){
			if (floor.getId() == null){
				continue;
			}
			if (Floor.DEL_FLAG_NORMAL.equals(floor.getDelFlag())){
				if (StringUtils.isBlank(floor.getId())){
					floor.setGroup(eleSourceFloor);
					floor.preInsert();
					floorDao.insert(floor);
				}else{
					floor.preUpdate();
					floorDao.update(floor);
				}
			}else{
				floorDao.delete(floor);
			}
		}
		for (FloorNode floor : eleSourceFloor.getFloornodes()){
			if (floor.getId() == null){
				continue;
			}
			if (Floor.DEL_FLAG_NORMAL.equals(floor.getDelFlag())){
				if (StringUtils.isBlank(floor.getId())){
					floor.setGroupId(eleSourceFloor.getId());
					floor.preInsert();
					floorNodeDao.insert(floor);
				}else{
					floor.preUpdate();
					floorNodeDao.update(floor);
				}
			}else{
				floorNodeDao.delete(floor);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(EleSourceFloor eleSourceFloor) {
		super.delete(eleSourceFloor);
		floorDao.delete(new Floor(eleSourceFloor));
	}
	
}